package com.hmdp.service.impl;

import ch.qos.logback.core.util.TimeUtil;
import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 生成验证码
     *
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //对手机号进行校验
        if (RegexUtils.isPhoneInvalid(phone)) { //手机号有效，验证通过
            return Result.fail("手机号码格式错误");
        }

        //校验成功->生成验证码
        final String code = RandomUtil.randomNumbers(6);
        //将验证码存储到redis中
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //打印到控制台
        log.debug("验证码：{}", code);

        return Result.ok();
    }

    /**
     * 用户登录
     *
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //进行手机号校验
        final String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误");
        }
        //进行验证码校验
        final String code = loginForm.getCode();//获取用户输入的验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        if (cacheCode == null || !cacheCode.equals(code)) {
            return Result.fail("验证码错误");
        }
        //根据手机号在数据库查询用户
        User user = query().eq("phone", phone).one();

        //如果没有查询到该用户，则创建用户
        if (user == null) {
            //创建用户
            user = creatWithPhone(phone);
        }
        //如果能查询到该用户，则将用户加入到redis中
            //生成随机的token，作为登录令牌（key）
            final String token = UUID.randomUUID().toString(true);//使用uuid作为token
            //将user对象转为hashmap存储（value）
            final UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
            final Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                                                CopyOptions
                                                .create()
                                                .setIgnoreNullValue(true)
                                                .setFieldValueEditor((fileldName, fieldValue) -> fieldValue.toString()));
            //存储到redis当中,并设置有效期
            String tokenKey = LOGIN_USER_KEY + token;
            stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
            stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
        //将token返回给前端
        return Result.ok(token);





    }

    /**
     * 实现签到功能
     * @return
     */
    @Override
    public Result sign() {
        //1.获取用户
        final Long userId = UserHolder.getUser().getId(); //获取用户ID
        //2.拼接redis前缀
        final LocalDateTime time = LocalDateTime.now(); //获取当前时间
        final String keysuffix = time.format(DateTimeFormatter.ofPattern(":yyyyMM")); //时间格式化
        String key = USER_SIGN_KEY + userId + keysuffix;
        //3.使用bitMap
        //3.1获取今天是本月的第几天
        final int day = time.getDayOfMonth();
        stringRedisTemplate.opsForValue().setBit(key, day - 1, true);

        return Result.ok();
    }

    /**
     * 实现连续签到统计功能
     * @return
     */
    @Override
    public Result signCount() {
        final Long userId = UserHolder.getUser().getId();
        //获取当前时间
        final LocalDateTime now = LocalDateTime.now();
        //拼接前缀
        final String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        //获取当天是本月的第几天
        final int day = now.getDayOfMonth();
        final List<Long> result = stringRedisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create().get(
                BitFieldSubCommands.BitFieldType.unsigned(day)).valueAt(0)
        );
        if (result == null || result.isEmpty()){
            return Result.ok(0);
        }
        Long num = result.get(0);
        if (num == null || num == 0){
            return Result.ok(0);
        }
        //设计一个计数器
        int count = 0;
        //循环遍历
        while (true){
            //让这个数与1做逻辑与运算
            if ((num & 1) == 0){ //反向判断 说明当天没有签到
                break;
            }
            count++;
            num = num >>> 1; //无符号右移
        }
        return Result.ok();
    }

    private User creatWithPhone(String phone) {
        final User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
